package com.weishi.project.training.controller;

import java.util.*;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.weishi.common.utils.SecurityUtils;
import com.weishi.common.utils.StringUtils;
import com.weishi.project.sport.trainingdata.vo.TypeValueVO;
import com.weishi.project.system.service.ISysDictDataService;
import com.weishi.project.training.domain.SportsmanBodyShape;
import com.weishi.project.training.service.ISportsmanBodyShapeService;
import com.weishi.project.training.service.impl.SportsmanServiceImplMethod;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.weishi.framework.aspectj.lang.annotation.Log;
import com.weishi.framework.aspectj.lang.enums.BusinessType;

import com.weishi.project.training.domain.Sportsman;
import com.weishi.project.training.service.ISportsmanService;
import com.weishi.framework.web.controller.BaseController;
import com.weishi.framework.web.domain.AjaxResult;
import com.weishi.common.utils.poi.ExcelUtil;
import com.weishi.framework.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * sportsmanController
 */
@Api(value = "运动员",description = "运动员")
@RestController
@RequestMapping("/training/sportsman")
public class SportsmanController extends BaseController {

    @Autowired
    private ISportsmanService sportsmanService;

    /**
     * 数据字典接口
     */
    @Autowired
    private ISysDictDataService dictDataService;



    /**
     * 查询运动员列表
     */
    @PreAuthorize("@ss.hasPermi('training:sportsman:list')")
    @GetMapping("/list")
    public TableDataInfo list(Sportsman sportsman) throws Exception {
        startPage();
        List<Sportsman> list = sportsmanService.selectSportsmanList(sportsman);
        return getDataTable(list);
    }


    @GetMapping("/listSportsmanCountByType")
    public AjaxResult listSportsmanCountByType() throws Exception {
        List<Map<String, Object>> list = sportsmanService.selectSportsmanCountByType();
        Map<String, Long> ret = new HashMap<>();
        long all=0,train=0,leave=0,injury=0;
        for(Map<String, Object> map : list){
            if(map.get("status").equals("0") || map.get("status").equals("2")){
                all += (long)map.get("num");
                train += (long)map.get("num");
            }if(map.get("status").equals("3")){
                leave += (long)map.get("num");
                all += (long)map.get("num");
            }if(map.get("status").equals("4")|| map.get("status").equals("5")|| map.get("status").equals("6")){
                all += (long)map.get("num");
                injury += (long)map.get("num");
            }
        }
        ret.put("all",all);
        ret.put("leave",leave);
        ret.put("train",train);
        ret.put("injury",injury);
        return AjaxResult.success(ret);
    }


    /**
     * 导出运动员列表
     */
    @PreAuthorize("@ss.hasPermi('training:sportsman:export')")
    @Log(title = "sportsman", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(Sportsman sportsman) throws Exception {
        List<TypeValueVO> typeValueVOList = dictDataService.getTypeValue("political_outlook");

        List<Sportsman> list = sportsmanService.selectSportsmanList(sportsman);
        list.forEach( p->{
                // 设置中文男女
            p.setGenderChinese(SportsmanServiceImplMethod.genderChinese(p.getSex()));
            // 设置群众面貌 （ 中文 ）
            p.setPoliticalOutlook(SportsmanServiceImplMethod.retPoliticalOutlook(typeValueVOList , p.getPoliticalOutlook()));
        });
        ExcelUtil<Sportsman> util = new ExcelUtil<Sportsman>(Sportsman.class);
        return util.exportExcel(list, "运动员列表");
    }


    @ApiOperation("导入列表数据")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) throws Exception
    {
        List<TypeValueVO> typeValueVOList = dictDataService.getTypeValue("political_outlook");
        ExcelUtil<Sportsman> util = new ExcelUtil<>(Sportsman.class);
        List<Sportsman> userList = util.importExcel(file.getInputStream());
        userList.forEach( sportsman-> {
            if(StringUtils.isNotEmpty(sportsman.getName())){
                Sportsman db = sportsmanService.qrySportsmanByName(sportsman.getName());
                if(db!=null){
                    sportsman.setId(db.getId());
                    sportsman.setSex(SportsmanServiceImplMethod.genderNumber(sportsman.getGenderChinese()));
                    // 设置群众面貌
                    sportsman.setPoliticalOutlook(SportsmanServiceImplMethod.importPoliticalOutlook(typeValueVOList , sportsman.getPoliticalOutlook()));
                    sportsmanService.updateById(sportsman);
                }else{
                    sportsman.setCtime(new Date());
                    sportsman.setStatus("0");
                    sportsman.setSex(SportsmanServiceImplMethod.genderNumber(sportsman.getGenderChinese()));
                    // 设置群众面貌
                    sportsman.setPoliticalOutlook(SportsmanServiceImplMethod.importPoliticalOutlook(typeValueVOList , sportsman.getPoliticalOutlook()));
                    sportsmanService.save(sportsman);
                }
            }

        });
        return AjaxResult.success();
    }


    @ApiOperation("导入列表模板")
    @GetMapping("/importTemplate")
    public AjaxResult importTemplate()
    {
        ExcelUtil<Sportsman> util = new ExcelUtil<>(Sportsman.class);
        return util.importTemplateExcel("模板数据");
    }


    /**
     * 获取运动员详细信息
     */
    //@PreAuthorize("@ss.hasPermi('training:sportsman:query')")
    @GetMapping("/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id) {
        Sportsman sportsman = sportsmanService.getById(id);

               // 返回数据
        return AjaxResult.success(sportsman);
    }


    /**
     * 新增运动员
     */
    @PreAuthorize("@ss.hasPermi('training:sportsman:add')")
    @Log(title = "sportsman", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Sportsman sportsman) {
        // 判断此用户是否已经注册
        Sportsman sportsmanName = sportsmanService.getOne(Wrappers.<Sportsman>lambdaQuery().eq(Sportsman::getName , sportsman.getName()));
        if(StringUtils.isNotNull(sportsmanName)){
            return AjaxResult.error("此用户已经注册！" );
        }
        sportsman.setCtime(new Date());
        if(StringUtils.isNotEmpty(sportsman.getPassword())){
            sportsman.setPassword(SecurityUtils.encryptPassword("123456"));  //用户密码
        }
        sportsmanService.save(sportsman);
        return AjaxResult.success();
    }


    /**
     * 修改运动员
     */
    @PreAuthorize("@ss.hasPermi('training:sportsman:edit')")
    @Log(title = "sportsman", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Sportsman sportsman) {
        sportsman.setLtime(new Date());
        sportsmanService.updateById(sportsman);
        return AjaxResult.success();
    }


    /**
     * 删除运动员
     */
    @PreAuthorize("@ss.hasPermi('training:sportsman:remove')")
    @Log(title = "sportsman", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids) {
        sportsmanService.removeByIds(Arrays.asList(ids));
        return AjaxResult.success();
    }


    @ApiOperation("运动员 -- 重置密码 123456")
    @RequestMapping(value = "/resetPassword", method = RequestMethod.POST)
    public AjaxResult resetPassword(@RequestBody JSONObject jsonObject)
    {
        Sportsman sportsman = new Sportsman();
        sportsman.setPassword(SecurityUtils.encryptPassword(jsonObject.getString("newPassWord")));  //用户密码
        sportsman.setAccountNumber(sportsmanService.getById(Integer.parseInt(jsonObject.get("id").toString())).getName());
        sportsman.setId(Integer.parseInt(jsonObject.get("id").toString()));
        sportsmanService.updateById(sportsman);
        return AjaxResult.success(jsonObject.getString("newPassWord"));
    }


    @ApiOperation("PC端 运动员 -- 修改密码")
    @RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
    public AjaxResult updatePassword(@RequestBody JSONObject jsonObject)
    {
        // 1，查询运动员是否存在
        Sportsman sport = sportsmanService.getById(Integer.parseInt(jsonObject.get("userId").toString()));
        Sportsman sportsman = new Sportsman();
        // 判断密码是否正确
        if(SecurityUtils.matchesPassword(jsonObject.get("password").toString() , sport.getPassword()) == false){
            return AjaxResult.error("修改失败，原密码错误！" );
        }
        sportsman.setPassword(SecurityUtils.encryptPassword(jsonObject.get("newPassword").toString()));
        sportsman.setId(sport.getId());
        sportsmanService.updateById(sportsman);
        return AjaxResult.success();
    }





}